<template>
  <view class="padding-bottom-button">
    <l-background has-sub-background />
    <view class="padding-30">
      <template v-if="type === 'overKilometer'">
        <view class="card">
          <l-form-cell v-model="price" unlined label="价格" placeholder="请输入每超1公里价格" :maxlength="5" suffix="元" />
        </view>
        <view class="margin-top-20">
          <text class="text-28 color-t1">价格范围：{{ adminInfo.overGte || 0 }} - {{ adminInfo.overLte || 0 }}元</text>
        </view>
      </template>

      <template v-else>
        <view class="card">
          <l-form-cell label="产品" label-width="auto" :value="setPriceVehicle.productName" disabled />
          <l-form-cell label="车型" :value="setPriceVehicle.brand + setPriceVehicle.seatAmount + '座'" unlined disabled />
        </view>

        <view class="card margin-top-16 padding-top-30">
          <view class="padding-lr-28">
            <l-title title="有效期" />
          </view>
          <l-form-cell label="开始时间" must has-slot @click="changeDate('startDate')">
            <text class="text-30" :class="['color-t' + (form.startDate ? 1 : 3)]">{{ form.startDate || '请选择日期' }}</text>
          </l-form-cell>
          <l-form-cell label="结束时间" must has-slot unlined @click="changeDate('endDate')">
            <text class="text-30" :class="['color-t' + (form.endDate ? 1 : 3)]">{{ form.endDate || '请选择日期' }}</text>
          </l-form-cell>
        </view>

        <view class="card margin-top-16 padding-top-30">
          <view class="padding-lr-28">
            <l-title title="设置价格" />
          </view>
          <l-form-cell v-model="form.price" label="价格" placeholder="请输入价格" :maxlength="5" suffix="元" unlined must />
        </view>

        <view v-for="(val,key) in priceList" :key="key" class="margin-top-20">
          <text class="text-28 color-t1">{{ val.showStartDate }} - {{ val.showEndDate }}价格范围：{{ val.seatAmountPriceGte || 0 }} - {{ val.seatAmountPriceLte || 0 }}元</text>
        </view>
      </template>
    </view>

    <tui-datetime ref="dateTime" :type="2" :end-year="endYear" :min-date="startDate" :set-date-time="setDateTime" @confirm="setDate" />

    <safe-area-bottom />
    <l-bottom-button text="确定" @click="confirm" />
  </view>
</template>

<script>
import { mapGetters } from 'vuex'
import { dateFormat, formVerify, checkDate } from '@/common/util'
import { addPrice, updatePrice, updateOverMileagePrice, getPlatformOverPriceLimit } from '../api'
export default {
  name: 'SetPrice',
  data() {
    const endYear = new Date().getFullYear() + 10
    return {
      endYear,
      startDate: '',
      type: 'add',
      price: '',
      form: {},
      setDateTime: '',
      set: '',
      verifyList: [
        { attr: 'startDate', toast: '请选择开始时间' },
        { attr: 'endDate', toast: '请选择结束时间' },
        { attr: 'price', toast: '请输入价格' }
      ],
      adminInfo: {},
      priceList: []
    }
  },
  computed: {
    ...mapGetters({
      setPriceVehicle: 'setPriceVehicle',
      userId: 'userId',
      userInfo: 'userInfo'
    })
  },
  onLoad(e) {
    this.init(e)
  },
  methods: {
    init(e) {
      this.type = e.type
      const info = this.setPriceVehicle

      if (e.type === 'overKilometer') {
        this.price = info.overMileagePrice || ''
        uni.setNavigationBarTitle({
          title: '设置超公里价格'
        })
        this.getPlatformOverPriceLimit()
      } else if (e.type === 'edit') {
        uni.setNavigationBarTitle({
          title: info.productName
        })
        this.getPlatformOverPriceLimit()
        this.form = {
          id: info.id,
          price: info.price,
          startDate: info.startDate,
          endDate: info.endDate,
          defaultPrice: 0
        }
      } else {
        uni.setNavigationBarTitle({
          title: '新增价格'
        })
        if (e.endDate) {
          const endDate = e.endDate.replace(/-/g, '/')
          this.startDate = dateFormat(new Date(endDate).getTime() + 1000 * 60 * 60 * 24)
        }
        this.form = {
          userId: this.userId,
          vehicleTypeId: info.vehicleTypeId,
          productId: info.productId,
          priceType: 2,
          price: '',
          startDate: '',
          endDate: '',
          defaultPrice: 0
        }
      }
    },
    // 获取平台价格限制
    async getPlatformOverPriceLimit() {
      const { fuelType, productId, seatAmount } = this.setPriceVehicle
      const [err, res] = await getPlatformOverPriceLimit({
        fuelType,
        productId,
        seatAmount
      })
      const data = res.data.data
      if (this.type === 'overKilometer') {
        this.adminInfo = data || {}
      } else {
        const { startDate, endDate } = this.form
        const list = data?.platformSeatAmountPrice || []
        const priceList = []
        list.forEach(item => {
          const { startTime, endTime } = item
          item.showStartDate = dateFormat(startTime, 'MM月DD日')
          item.showEndDate = dateFormat(endTime, 'MM月DD日')
          if (this.getDateTime(startDate) >= this.getDateTime(startTime) && this.getDateTime(startDate) <= this.getDateTime(endTime)) {
            return priceList.push(item)
          }
          if (this.getDateTime(endDate) >= this.getDateTime(startTime) && this.getDateTime(endDate) <= this.getDateTime(endTime)) {
            return priceList.push(item)
          }
          if (this.getDateTime(startDate) < this.getDateTime(startTime) && this.getDateTime(endDate) > this.getDateTime(endTime)) {
            return priceList.push(item)
          }
        })
        this.priceList = priceList
      }
    },
    // 转换时间戳
    getDateTime(date) {
      date = date.replace(/-/g, '/')
      const time = new Date(date).getTime()
      return time
    },
    // 显示修改时间
    changeDate(attr) {
      this.setDateTime = this.form[attr] || this.startDate || dateFormat()

      if (this.set !== attr) this.$refs.dateTime.initData()

      this.set = attr
      this.$refs.dateTime.show()
    },
    // 确认修改时间
    setDate(e) {
      this.form[this.set] = e.result
      if (checkDate(this.form.startDate, this.form.endDate)) {
        this.getPlatformOverPriceLimit()
      }
    },
	toast(data){
		uni.showToast({
		     title: data,
		     icon: 'none',
		     duration: 2000//持续的时间
		   })
	},
    // 确认修改
    confirm() {
		let numberRegex;
	if(this.type === 'overKilometer'){
		numberRegex = /^\d+(\.\d{1,2})?$/;
		if(!numberRegex.test(this.price)){
			  this.toast('公里价格请输入最多两位小数的数据类型')
			  return false
		}
		if(this.price.length>5){
			this.toast('公里价格最大输入5位数')
			return false
		}
	}else{
		numberRegex = /^\d+(\.\d{1})?$/;
		if(!numberRegex.test(this.form.price)){
			  this.toast('价格请输入最多一位小数的数据类型')
			  return false
		}
		if(this.form.price.length>6){
			this.toast('价格最大输入六位数')
			return false
		}
	}
      if (this.type === 'overKilometer') this.updateProductPrice()
      else this.setPrice()
    },
    // 修改价格
    async setPrice() {
      if (formVerify(this.form, this.verifyList) && checkDate(this.form.startDate, this.form.endDate)) {
        if (this.priceList.length > 1) {
          this.toast('该日期范围内存在多个价格，请重新选择日期范围')
          return
        }
        if (this.priceList.length && (this.form.price < this.priceList[0].seatAmountPriceGte || this.form.price > this.priceList[0].seatAmountPriceLte)) {
          this.toast('请输入范围内的价格')
          return
        }

        let api = addPrice
        let toast = '添加成功'
        if (this.type === 'edit') {
          api = updatePrice
          toast = '修改成功'
        }
        const [err, res] = await api(this.form)
        if (!this.$http.errorCheck(err, res)) return false
		this.toast(toast)
		let _then = this
		setTimeout(function() {
			_then.jump()
		}, 2000);
      }
    },
    // 设置超公里价格
    async updateProductPrice() {
      const { overGte, overLte } = this.adminInfo
      if (this.price < overGte || this.price > overLte) {
        this.toast('请输入范围内的价格')
        return
      }
      const [err, res] = await updateOverMileagePrice({
        autoCompanyId: this.userInfo.companyId,
        vehicleTypeId: this.setPriceVehicle.vehicleTypeId,
        price: this.price,
		productId:this.setPriceVehicle.productId
		
      })
      if (!this.$http.errorCheck(err, res)) return false
	  this.toast('设置价格成功')
	  let _then = this
	  setTimeout(function() {
	  	_then.jump()
	  }, 2000);
    }
  }
}
</script>

<style scoped lang="scss">
@include setPadding(lr,28);
</style>
